<?php

require_once ROOT_DIR.'models/Todo.php';
require_once ROOT_DIR.'models/TodoList.php';
require_once ROOT_DIR.'views/TodoJSON.php';
require_once ROOT_DIR.'controls/RightHelper.php';

/**
 * Tries to link a todo with a list and echos the resulting view
 * @param int $todoID
 * @param int $listID
 */
function addTodoToList($todoID, $listID){
	
	$list = TodoList::getList($listID);
	$todo = Todo::getTodo($todoID);
	
	if(!is_null($list)){
		if(!is_null($todo)){
			if($_SESSION['USER_NAME'] == 'admin' || ($list->getOwnerID() == $_SESSION['USER_ID'] && ($todo->getCreatorID() == $_SESSION['USER_ID'] || RightHelper::checkIfLinkedToTodo($todo)))){
				$res = Todo::linkTodoWithList($todoID, $listID);
				if($res){
					$res = new ResultJSON(false, session_id());
					echo $res->renderView();
				} else {
					$res = new ResultJSON(true, session_id(), ERROR_ACTION_FAILED);
					echo $res->renderView();
				}
			} else {
				$res = new ResultJSON(true, session_id(), ERROR_NOT_ALLOWED);
				echo $res->renderView();
			}
		} else {
			$res = new ResultJSON(true, session_id(), ERROR_TODO_DOES_NOT_EXIST);
			echo $res->renderView();
		}
	} else {
		$res = new ResultJSON(true, session_id(), ERROR_LIST_DOES_NOT_EXIST);
		echo $res->renderView();
	}
}

?>